<?php

namespace Largezhou\Admin\Commands;

use App\Models\Menu;
use Illuminate\Console\Command;

class InstallMenus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'admin:menus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '初始化后台菜单';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->info('正在生成后台默认菜单...');

        $menus = require __DIR__.'/./data/menus.php';

        $menus = $this->flatten($menus);

        Menu::truncate();
        Menu::insert($menus);

        $this->info('生成菜单完成');
    }

    protected function flatten($menus, $parentId = 0, &$id = 1)
    {
        $data = [];

        foreach ($menus as $menu) {
            $menu['id'] = $id;
            $menu['order'] = $id;
            $menu['parent_id'] = $parentId;
            $data[] = $menu;

            $id++;

            if (array_key_exists('children', $menu)) {
                unset($data[count($data) - 1]['children']);

                if (count($menu['children']) > 0) {
                    $data = array_merge($data, $this->flatten($menu['children'], $id - 1, $id));
                }
            }
        }

        return $data;
    }
}
